//
//  CalcView.swift
//  CrseAsst
//
//  Created by 申铭 on 2024/3/5.
//

import SwiftUI

struct CalcView: View {
    let type: CalcType
    
    @State private var title = "00:00"
    @State private var totalSeconds: Int = 0
    
    @StateObject
    private var vm = CalcViewModel()
    
    @State private var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    
    var body: some View {
        VStack {
            HStack {
                Text(vm.countTips)
                    .padding(.leading, 15)
                Spacer()
                if vm.showResult {
                    if vm.isRight {
                        Image(systemName: "checkmark")
                            .foregroundColor(.green)
                            .padding(.trailing, 15)
                    } else {
                        Image(systemName: "xmark")
                            .foregroundColor(.red)
                            .padding(.trailing, 15)
                    }
                }
            }
            .padding(.top, 30)
            .onReceive(timer, perform: { _ in
                totalSeconds += 1
                title = totalSeconds.toSecondStr()
            })
            
            MathLabel(text: vm.ques, fontSize: 35)
                .frame(width: 300, height: 70)
            MathLabel(text: vm.answerText, fontSize: 35)
                .frame(width: 300, height: 70)
            
            CustomKeyBoardTextField(text: $vm.answerText, returnKeyBlock: {
                vm.next()
            }, specialKeyBlock: { type in
            })
            .opacity(0)
            
            Spacer()
            
            // TODO: MAC平台如何使用回车键确认结果
            
//            Button(action: {
//                log.verbose("11123123")
//            }, label: {
//                EmptyView()
//            })
//            .keyboardShortcut(.defaultAction)
            
        }
        .onAppear(perform: {
            vm.setType(type)
        })
        .navigationTitle(title)
        .navigationBarTitleDisplayMode(.inline)
        .navigationBarItems(trailing: NavigationLink(destination: {
            CalcSettingView()
        }, label: {
            Label("", systemImage: "gearshape")
        }))
    }
}

#Preview {
    CalcView(type: .twoDigitAdd)
}
